package com.mf.morefun.ui.myclass;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mf.morefun.R;
import com.mf.morefun.adapter.HomeWorkCountAdapter;
import com.mf.morefun.base.BaseBusActivity;
import com.mf.morefun.bean.DoHomeWorkBean;
import com.mf.morefun.bean.DoHomeWorkListBean;
import com.mf.morefun.bean.ResultBean;
import com.mf.morefun.constant.Configuration;
import com.mf.morefun.listener.HomeWorkCountListener;
import com.mf.morefun.requestbean.RequestHomeWorkCountBean;
import com.mf.morefun.ui.VideoActivity;
import com.mf.morefun.ui.comment.CommentActivity;
import com.mf.morefun.ui.dohomework.LiteraryCreationActivity;
import com.mf.morefun.widget.NetErrorPop;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhcx.zhcxlibrary.utils.DateUtils;
import com.zhcx.zhcxlibrary.utils.SPUtils;
import com.zhcx.zhcxlibrary.utils.StringUtils;
import com.zhcx.zhcxlibrary.utils.ToastUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomeWorkCountActivity extends BaseBusActivity {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.elv_homework)
    ExpandableListView elvHomework;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private ClassicsHeader mClassicsHeader = null;
    private int pageNo = 1;
    private int totlePage = 1;
    private String classId, homeworkId;
    private SPUtils mSPUtils;
    private Map<String, List<DoHomeWorkListBean>> mHomeWorkMap = new HashMap<>();
    private List<DoHomeWorkListBean> mDoHomeWorkList = new ArrayList<>();
    private HomeWorkCountAdapter adapter;
    @Override
    protected int getNaviteColor() {
        return 0;
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_homeworkcount;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mSPUtils = new SPUtils(getApplicationContext());
        classId = getIntent().getStringExtra("CLASSID");
        homeworkId = getIntent().getStringExtra("HOMEWORKID");
        tvName.setText("作业(" + getIntent().getStringExtra("HOMEWORKNAME") + ")");
        mClassicsHeader = (ClassicsHeader) refreshLayout.getRefreshHeader();
        int delda = new Random().nextInt(7 * 24 * 60 * 60 * 1000);
        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis() - delda));
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        refreshLayout.getLayout().bringChildToFront(elvHomework);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                if (!StringUtils.isEmpty(classId) && !StringUtils.isEmpty(homeworkId)){
                    initGetHomeWorkList(classId, homeworkId, true);
                }
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNo++;
                if (pageNo < totlePage) {
                    if (!StringUtils.isEmpty(classId) && !StringUtils.isEmpty(homeworkId)){
                        initGetHomeWorkList(classId, homeworkId, false);
                    }
                } else {
                    if (null != refreshLayout) {
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                        refreshLayout.setEnableLoadMore(false);
                    }
                }
            }
        });
        if (!StringUtils.isEmpty(classId) && !StringUtils.isEmpty(homeworkId)){
            initGetHomeWorkList(classId, homeworkId, true);
        }
        adapter = new HomeWorkCountAdapter(HomeWorkCountActivity.this, mHomeWorkMap, mDoHomeWorkList);
        elvHomework.setAdapter(adapter);
        elvHomework.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                return true;
            }
        });
        adapter.setListener(new HomeWorkCountListener() {
            @Override
            public void callBack(int groupPosition, int childPosition, int type) {
                try {
                    if (mDoHomeWorkList.size() > 0 && mHomeWorkMap.size() > 0){
                        if (type == 0) {
                            Intent mIntent = new Intent(HomeWorkCountActivity.this, LiteraryCreationActivity.class);
                            mIntent.putExtra(Configuration.USERID, mSPUtils.getString(Configuration.USERID));
                            if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR()){
                                mIntent.putExtra("TPBUS", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getId());
                                mIntent.putExtra("TPDETAILID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getId());
                                mIntent.putExtra("TP", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getTp().getId());
                            }
                            if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation()) {
                                mIntent.putExtra("TITLE", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation().getName());
                                mIntent.putExtra("DESCRIPTION", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation().getTextDescription());
                            }
                            mIntent.putExtra("CLASSID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getClassId());
                            startActivityForResult(mIntent, 0);
                        } else if (type == 1) {
                            Intent mIntent = new Intent(HomeWorkCountActivity.this, CommentActivity.class);
                            mIntent.putExtra(Configuration.HOMEWORK, caluateDate(DateUtils.DATE_YEAR_MONTH_DAY.format(new Date(System.currentTimeMillis())), mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getEndDate()));
                            mIntent.putExtra("TYPE", "1");
                            mIntent.putExtra(Configuration.USERID, mSPUtils.getString(Configuration.USERID));
                            if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation()){
                                mIntent.putExtra("TITLE", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation().getName());
                                mIntent.putExtra("DESCRIPTION", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation().getTextDescription());
                            }
                            if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR()){
                                mIntent.putExtra("TPBUS", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getId());
                                mIntent.putExtra("TPDETAILID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getId());
                                mIntent.putExtra("TP", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getTp().getId());
                            }
                            if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord()) {
                                mIntent.putExtra("MFRECORDID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getId());
                                if (mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getType().equals("5")) {
                                    mIntent.putExtra("ISVIDEO", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getAudio());
                                }
                                if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getUser()) {
                                    mIntent.putExtra("STUDENT", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getUser().getId());
                                }
                                if (!StringUtils.isEmpty(mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCommentFlag())){
                                    if (mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCommentFlag().equals("1")) {//有点评才会传值过去
                                        mIntent.putExtra("MFCOMMENT", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpComment());
                                    }
                                }
                            }
                            mIntent.putExtra("CLASSID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getClassId());
                            startActivity(mIntent);
                        } else {
                            if (type != 2) {//创作
                                Intent mIntent = new Intent(HomeWorkCountActivity.this, CommentActivity.class);
                                mIntent.putExtra(Configuration.HOMEWORK, caluateDate(DateUtils.DATE_YEAR_MONTH_DAY.format(new Date(System.currentTimeMillis())), mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getEndDate()));
                                mIntent.putExtra("BOOKID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getBook().getId());
                                mIntent.putExtra(Configuration.USERID, mSPUtils.getString(Configuration.USERID));
                                mIntent.putExtra("BOOKNAME", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getBook().getName());
                                mIntent.putExtra("TYPE", "1");
                                mIntent.putExtra("CLASSID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getClassId());
                                mIntent.putExtra("TPBUS", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getId());
                                mIntent.putExtra("TPDETAILID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getId());
                                mIntent.putExtra("TP", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getTp().getId());
                                if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord()) {
                                    mIntent.putExtra("MFRECORDID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getId());
                                    if (mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getType().equals("5")) {
                                        mIntent.putExtra("ISVIDEO", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getAudio());
                                    }
                                    if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getUser()) {
                                        mIntent.putExtra("STUDENT", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpRecord().getUser().getId());
                                    }
                                }
                                if (!StringUtils.isEmpty(mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCommentFlag())){
                                    if (mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCommentFlag().equals("1")){//有点评才会传值过去
                                        mIntent.putExtra("MFCOMMENT", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpComment());
                                    }
                                }
                                startActivity(mIntent);
                            }else {
                                //进入视频
                                Intent mIntent = new Intent(HomeWorkCountActivity.this, VideoActivity.class);
                                mIntent.putExtra(Configuration.USERID, mSPUtils.getString(Configuration.USERID));
                                if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR()) {
                                    mIntent.putExtra("TPBUS", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getId());
                                    mIntent.putExtra("TPDETAILID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getId());
                                    mIntent.putExtra("TP", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getTpDetail().getTp().getId());
                                    mIntent.putExtra("type", "4");
                                    mIntent.putExtra("BOOKID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpLRR().getBook().getId());
                                }else if (null != mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation()) {
                                    mIntent.putExtra("TPBUS", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation().getId());
                                    mIntent.putExtra("TPDETAILID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfTpCreation().getTeachingProgramDetail().getId());
                                    mIntent.putExtra("type", "4");
                                }
                                mIntent.putExtra("VIDEO", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getMfVideo().getAddress());
                                mIntent.putExtra("CLASSID", mHomeWorkMap.get(mDoHomeWorkList.get(groupPosition).getMfTpLRR().getName()).get(childPosition).getClassId());
                                startActivity(mIntent);
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    ToastUtils.show(getApplicationContext(), "MfTpLRR为空", 100);
                }
            }
        });
    }

    private boolean caluateDate(String startDate, String endDate) {
        boolean isAble = false;
        if (StringUtils.isEmpty(startDate)) {
            return false;
        }
        if (StringUtils.isEmpty(endDate)) {
            return false;
        }
        String start[] = startDate.split("-");
        String end[] = endDate.split("-");
        if (start.length != 3) {
            return false;
        }
        if (end.length != 3) {
            return false;
        }
        try {
            int year = Integer.parseInt(end[0]) - Integer.parseInt(start[0]);
            int month = Integer.parseInt(end[1]) - Integer.parseInt(start[1]);
            int day = Integer.parseInt(end[2]) - Integer.parseInt(start[2]);
            int time = (year * 365 + month * 30 + day);
            if (time < 0) {
                isAble = false;
            } else {
                isAble = true;
            }
        } catch (Exception e) {
            isAble = false;
            e.printStackTrace();
        }
        return isAble;
    }

    private void initGetHomeWorkList(String classId, String homeworkId, boolean isRefresh) {
        RequestParams params = new RequestParams(Configuration.HOST + Configuration.DOHOMEWORKLIST);
        RequestHomeWorkCountBean requestHomeWorkCountBean = new RequestHomeWorkCountBean();
        requestHomeWorkCountBean.setOrderBy("tpcdr.start_date desc");
        requestHomeWorkCountBean.setPageNo(pageNo);
        requestHomeWorkCountBean.setPageSize(20);
        RequestHomeWorkCountBean.MfTpPageDataBean mfTpPageDataBean = new RequestHomeWorkCountBean.MfTpPageDataBean();
        mfTpPageDataBean.setClassId(classId);
        mfTpPageDataBean.setUserId(mSPUtils.getString(Configuration.USERID));
        mfTpPageDataBean.setMfTpRecordFlag("1");
        RequestHomeWorkCountBean.MfTpPageDataBean.MfTpRecordBean mfTpRecordBean = new RequestHomeWorkCountBean.MfTpPageDataBean.MfTpRecordBean();
        RequestHomeWorkCountBean.MfTpPageDataBean.MfTpRecordBean.TpDetailBean tpDetailBean = new RequestHomeWorkCountBean.MfTpPageDataBean.MfTpRecordBean.TpDetailBean();
        tpDetailBean.setId(homeworkId);
        mfTpRecordBean.setTpDetail(tpDetailBean);
        mfTpPageDataBean.setMfTpRecord(mfTpRecordBean);
        requestHomeWorkCountBean.setMfTpPageData(mfTpPageDataBean);
        params.setBodyContent(JSON.toJSONString(requestHomeWorkCountBean));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (null != refreshLayout) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                if (isRefresh) {
                    mHomeWorkMap.clear();
                    mDoHomeWorkList.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    ResultBean resultBean = JSON.parseObject(result, ResultBean.class);
                    if (resultBean.getErrorCode() == 0) {
                        if (!StringUtils.isEmpty(resultBean.getResult())) {
                            DoHomeWorkBean doHomeWorkBean = JSON.parseObject(resultBean.getResult(), DoHomeWorkBean.class);
                            totlePage = doHomeWorkBean.getTotalPage();
                            if (!StringUtils.isEmpty(doHomeWorkBean.getList())) {
                                List<DoHomeWorkListBean> mHomeWorkList = JSON.parseArray(doHomeWorkBean.getList(), DoHomeWorkListBean.class);
                                mDoHomeWorkList.addAll(mHomeWorkList);
                                caluate(mDoHomeWorkList);
                            }
                        }
                    }
                    mHandler.sendEmptyMessage(100);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                if (null != refreshLayout) {
                    refreshLayout.finishLoadMore();
                    refreshLayout.finishRefresh();
                }
                mHandler.sendEmptyMessage(101);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void caluate(List<DoHomeWorkListBean> mHomeWorkList) {
        if (null != mHomeWorkList && mHomeWorkList.size() > 0){
            if (mHomeWorkList.size() > 0){
                for (int i = 0; i < mHomeWorkList.size(); i++){
                    if (null != mHomeWorkList.get(i).getMfTpRecordPageDataList() && mHomeWorkList.get(i).getMfTpRecordPageDataList().size() > 0){
                        if (null != mHomeWorkList.get(i).getMfTpLRR()){
                            mHomeWorkMap.put(mHomeWorkList.get(i).getMfTpLRR().getName(), mHomeWorkList.get(i).getMfTpRecordPageDataList());
                        }else {
                            mHomeWorkMap.put("未知", mHomeWorkList.get(i).getMfTpRecordPageDataList());
                        }
                    }else {
                        List<DoHomeWorkListBean> mDoHomeWorkList = new ArrayList<>();
                        if (null != mHomeWorkList.get(i).getMfTpLRR()){
                            mHomeWorkMap.put(mHomeWorkList.get(i).getMfTpLRR().getName(), mDoHomeWorkList);
                        }else {
                            mHomeWorkMap.put("未知", mDoHomeWorkList);
                        }
                    }
                }
            }
        }
    }

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 101:
                    NetErrorPop errorPop = new NetErrorPop(HomeWorkCountActivity.this);
                    errorPop.showPop("");
                    break;
                case 100:
                    //刷新适配器
                    if (null != adapter){
                        adapter.notifyDataSetChanged();
                        if (mDoHomeWorkList.size() > 0){
                            for (int i = 0; i < mDoHomeWorkList.size(); i++){
                                elvHomework.expandGroup(i);
                            }
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void initData() {

    }

    @OnClick(R.id.iv_back)
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
        }
    }
}
